<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>workerman-chat PHP聊天室 Websocket(HTLM5/Flash)+PHP多进程socket实时推送技术</title>
    <link href="/chat/css/bootstrap.min.css" rel="stylesheet">
    <link href="/chat/css/jquery-sinaEmotion-2.1.0.min.css" rel="stylesheet">
    <link href="/chat/css/style.css" rel="stylesheet">

    <script type="text/javascript" src="/chat/js/swfobject.js"></script>
    <script type="text/javascript" src="/chat/js/web_socket.js"></script>
    <script type="text/javascript" src="/chat/js/jquery.min.js"></script>
    <script type="text/javascript" src="/chat/js/jquery-sinaEmotion-2.1.0.min.js"></script>

    <!--    <script type="text/javascript">-->
    <!--        var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");-->
    <!--        document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F7b1919221e89d2aa5711e4deb935debd' type='text/javascript'%3E%3C/script%3E"));-->
    <!--    </script>-->
    <style>
        .no {
            text-align: center;
            margin-top: 1rem;
        }

        .no .text {
            background-color: #D3D3D3;
            padding: 0 2rem 0 2rem;
        }
    </style>
</head>
<body onload="connect();">
<div class="container">
    <div class="row clearfix">
        <div class="col-md-1 column">
        </div>
        <div class="col-md-6 column">
            <div class="thumbnail" style="height: 500px;">
                <div class="caption" id="dialog" style="height: 100%;min-height : 0">

                </div>
            </div>
            <form onsubmit="onSubmit(); return false;">
                <select style="margin-bottom:8px" id="client_list">
                    <option value="all">所有人</option>
                </select>
                <textarea class="textarea thumbnail" id="textarea"></textarea>
                <div class="say-btn">
                    <input type="button" class="btn btn-default face pull-left" value="表情"/>
                    <input type="submit" class="btn btn-default" value="发表"/>
                </div>
            </form>
            <div>
                <b>房间列表:</b>（当前在 房间 {$res} ）<br>
                <a href="/?room_id=1">房间1</a>
                <a href="/?room_id=2">房间2</a>
                <a href="/?room_id=3">房间3</a>
                <a href="/?room_id=4">房间4</a>
                <br><br>
            </div>
            <p class="cp">PHP多进程+Websocket(HTML5/Flash)+PHP Socket实时推送技术&nbsp;&nbsp;&nbsp;&nbsp;Powered by
                <a href="http://www.workerman.net/workerman-chat" target="_blank">workerman-chat</a>
            </p>
        </div>
        <div class="col-md-3 column">
            <div class="thumbnail">
                <div class="caption">
                    <ul id="userlist">

                    </ul>
                </div>
            </div>
            <a href="http://workerman.net:8383" target="_blank">
                <img style="width:252px;margin-left:5px;" src="/img/workerman-todpole.png">
            </a>
        </div>
    </div>
</div>
<script>
    if (typeof console == "undefined") {
        this.console = {
            log: function (msg) {
            }
        };
    }
    // 如果浏览器不支持websocket，会使用这个flash自动模拟websocket协议，此过程对开发者透明
    WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
    // 开启flash的websocket debug
    WEB_SOCKET_DEBUG = true;
    var ws, name, client_list = {}, room_id = {$res};

    //连接服务器
    function connect() {
        // 创建websocket
        ws = new WebSocket("ws://127.0.0.1:7272");
        // 当socket连接打开时，输入用户名
        ws.onopen = onopen;
        // 当有消息时根据消息类型显示不同信息
        ws.onmessage = onmessage;
        ws.onclose = function () {
            console.log("连接关闭，定时重连");
            connect();
        };
        ws.onerror = function () {
            console.log("出现错误");
        };
    }

    // 连接建立时发送登录信息
    function onopen() {
        if (!name) {
            console.log(123231)
            name = prompt('输入你的名字：', '');
            if (!name || name === 'null') {
                name = '游客';
            }
        }
        ws.send('123123');
        // getChatList(room_id);
    }


    // 提交对话
    function onSubmit() {
        let input = document.getElementById("textarea"),
            content = input.value.replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
        $.ajax({
            type: 'POST',
            url: '/chat/addSpeak',
            data: {'name': name.replace(/"/g, '\\"'), 'roomId': room_id, 'content': content},
            dataType: 'json',
            success: function (res) {
            },
            error: function (res) {
            },
        });
        input.value = "";
        input.focus();
    }

    // 服务端发来消息时
    function onmessage(e) {
        // console.log(e.data)
        let data = JSON.parse(e.data);
        switch (data['type']) {
            // 服务端ping客户端
            case 'ping':
                ws.send('{"type":"pong"}');
                break;
            case 'init':
                bingClientId(data['client_id']);
                break;
            case 'addNotice':
                addNotice(data);
                getChatList(room_id);
                break;
            case 'refreshList':
                chatList(data);
                break;
            case 'speak':
                speak(data);
                break;
            case 'leaveNotice':
                leaveNotice(data);
                getChatList(room_id);
        }
    }


    // 发言
    function speak(data) {
        let div = $("#dialog"),
            html = '<div class="speech_item">' +
            data['client_name'] + ' <br>'  +
            data['time'] +
            '<div style="clear:both;">' +
            '</div>' +
            '<p class="triangle-isosceles top">' + data['content'] + '</p> </div>';

        div.append(html).parseEmotion();
        if ((div[0].scrollHeight > div[0].clientHeight) || (div[0].offsetHeight > div[0].clientHeight)) {
            div[0].scrollTop = div[0].scrollHeight; //控制scrollTop的值
        }
    }

    //绑定
    function bingClientId(client_id) {
        $.ajax({
            type: 'POST',
            url: '/chat/bingUser',
            data: {'clientId': client_id, roomId: room_id, name: name},
            dataType: 'json',
            success: function (res) {
            },
            error: function (res) {
            }
        });
    }

    //在线用户列表
    function getChatList(room_id) {
        $.ajax({
            type: 'POST',
            url: '/chat/onlineList',
            data: {'roomId': room_id, name: name},
            dataType: 'json',
            success: function (res) {
                let html = ' <h4>在线用户列表</h4>';
                if (res.data) {
                    $.each(res.data, function (index, value) {
                        html += '<li id="' + value.session_id + '">' + value.name + '</li>';
                    });
                }
                $('#userlist').html(html);
            },
            error: function (res) {

            }
        });
    }

    //加入聊天室通知
    function addNotice(data) {
        let html = ' <div class="no"><span class="text">' + data['client_name'] + '加入聊天室</span></div>';
        $('#dialog').append(html);
    }

    //离开聊天室
    function leaveNotice(data) {
        let html = ' <div class="no"><span class="text">' + data['client_name'] + '离开聊天室</span></div>';
        $('#dialog').append(html);
    }

    function chatList() {

    }

    $(function () {
        select_client_id = 'all';
        $("#client_list").change(function () {
            select_client_id = $("#client_list option:selected").attr("value");
        });
        $('.face').click(function (event) {
            $(this).sinaEmotion();
            event.stopPropagation();
        });
    });


</script>
<script>
    // 动态自适应屏幕
    document.write('<meta name="viewport" content="width=device-width,initial-scale=1">');
    $("textarea").on("keydown", function (e) {
        // 按enter键自动提交
        if (e.keyCode === 13 && !e.ctrlKey) {
            e.preventDefault();
            $('form').submit();
            return false;
        }

        // 按ctrl+enter组合键换行
        if (e.keyCode === 13 && e.ctrlKey) {
            $(this).val(function (i, val) {
                return val + "\n";
            });
        }
    });
</script>
</body>
</html>